/*
 * ip_camera.cpp
 *
 *  Created on: Oct 27, 2010
 *      Author: Alexey Brodkin
 */

#include "QIpCamera.h"
#include <QDebug>
#include <QPixmap>


QIpCamera::QIpCamera(int i, QString url_string)
{
    instance = i;
    inited = false;
    network_manager = new QNetworkAccessManager(this);
    connect(network_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(slot_network_manager_finished(QNetworkReply*)));
    
    url = new QUrl(url_string);
    if (!url->isValid()) {
        qWarning() << "Invalid url" << url;
        return;
    }

    inited = true;
    active = false;
    timer = new QTimer(this);
    timer->setSingleShot(true);
    connect(timer, SIGNAL(timeout()), this, SLOT(slot_timer_timeout()));
}

QIpCamera::~QIpCamera()
{
    delete timer;
    delete url;
    delete network_manager;    
}

void QIpCamera::setPeriod(int period)
{
    timer->setInterval(period);
}

bool QIpCamera::isInitialized()
{
    return inited;
}

void QIpCamera::start()
{
    active = true;
    timer->stop();
    slot_timer_timeout();
}

void QIpCamera::stop()
{
    active = false;
    timer->stop();
}

void QIpCamera::slot_timer_timeout()
{
    QNetworkRequest request(*url);
    network_manager->get(request);
}

void QIpCamera::slot_network_manager_finished(QNetworkReply * reply)
{
    QPixmap pixmap;
    
    if (reply->error() != QNetworkReply::NoError) {
        qWarning() << "Error in" << reply->url() << ":" << reply->errorString();
    }
    else
    if (reply->header(QNetworkRequest::ContentTypeHeader).toString() != QString("image/jpeg")) {
        qWarning() << "Unexpected content type:" << reply->header(QNetworkRequest::ContentTypeHeader).toString();
    }
    else {
        QByteArray jpeg_data = reply->readAll();            
        pixmap.loadFromData(jpeg_data);            
    }
    
    emit newImage(instance, pixmap);

    if (active)
        timer->start();

    reply->deleteLater();
    
    return;
}

